package com.zx.chatroom.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.zx.chatroom.listener.HallListener;
import com.zx.chatroom.listener.TalkListener;
import com.zx.chatroom.po.Dept;
import com.zx.chatroom.po.GroupChat;
import com.zx.chatroom.po.Role;
import com.zx.chatroom.po.User;
import com.zx.chatroom.po.UserExt;
import com.zx.chatroom.service.DeptService;
import com.zx.chatroom.service.GroupChatService;
import com.zx.chatroom.service.LoginService;
import com.zx.chatroom.service.RoleService;
import com.zx.chatroom.util.CONST;
import com.zx.chatroom.vo.UserVo;
import com.zx.framework.core.exception.ActionException;
import com.zx.framework.core.util.StringUtil;
import com.zx.framework.web.action.spring.BaseController;

@Controller
@RequestMapping("/login")
public class LoginAction extends BaseController{

	private static final Logger LOGGER = Logger.getLogger(LoginAction.class);
	@Resource
	private LoginService loginService;
	@Resource
	private DeptService deptService;
	@Resource
	private RoleService roleService;
	@Resource
	private GroupChatService groupChatService;
	/**
	 * 坐席登录
	 * @param model
	 * @param baseId 用户主键ID
	 * @return
	 */
	@RequestMapping(value = "/seat", method = {RequestMethod.POST,RequestMethod.GET} )
	public String seat(Model model,@RequestParam("baseId") String baseId) {
		if (StringUtil.isEmpty(baseId)) {
			throw new ActionException("参数不能为空！");
		}
//		try {
//			baseId = AESUtil.decryptAES(baseId);
//		} catch (Exception e) {
//			throw new ActionException("解密失败，请勿非法尝试！");
//		}
		User user = loginService.findUserById(baseId);
		if (null == user) {
			throw new ActionException("未找到用户信息，无法登陆！");
		}
		UserExt userExt = loginService.findUserExtById(user.getId());
		List<Dept> userDepts = deptService.findUserDeptByUserId(user.getId());
		UserVo userVo = new UserVo();
		userVo.setId(user.getId());
		userVo.setLoginid(user.getLoginId());
		if (!userDepts.isEmpty()) {
			userVo.setDept(userDepts.get(0).getName());
		} else {
			userVo.setDept("未知部门");
		}
		if (StringUtil.isEmpty(userVo.getDept()) || userVo.getDept().indexOf("特许厅") != -1) {
			throw new ActionException("特许厅人员无权登陆在线客服！");
		}
		userVo.setUsername(user.getUserName());
		if (null != userExt) {
			userVo.setIp(StringUtil.isNotEmpty(userExt.getIp()) ? userExt.getIp() : "暂无");
			userVo.setPhone(StringUtil.isNotEmpty(userExt.getMobile()) ? userExt.getMobile() : "暂无");
		}
		HallListener.USER_LIST.put(user.getId(), userVo);
		model.addAttribute("userjson", gson.toJson(userVo));
		model.addAttribute("userName", userVo.getUsername());
		initEnv(model);
		//model.addAttribute("basePath", "/chatroom/");
		return "seat";
	}
	/**
	 * 营业员登录
	 * @param model
	 * @param baseId 用户主键ID
	 * @return
	 */
	@RequestMapping(value = "/visit", method = {RequestMethod.POST,RequestMethod.GET} )
	public String visit(Model model,@RequestParam("baseId") String baseId) {
		seat(model, baseId);
		return "visit";
	}
	
	@RequestMapping(value = "/talk", method = {RequestMethod.POST,RequestMethod.GET} )
	public String talk(Model model,@RequestParam("baseId") String baseId) {
		if (StringUtil.isEmpty(baseId)) {
			throw new ActionException("参数不能为空！");
		}
//		try {
//			baseId = AESUtil.decryptAES(baseId);
//		} catch (Exception e) {
//			throw new ActionException("解密失败，请勿非法尝试！");
//		}
		User user = loginService.findUserById(baseId);
		if (null == user) {
			throw new ActionException("未找到用户信息，无法登陆！");
		}
		UserExt userExt = loginService.findUserExtById(user.getId());
		List<Dept> userDepts = deptService.findUserDeptByUserId(user.getId());
		UserVo userVo = new UserVo();
		userVo.setId(user.getId());
		userVo.setLoginid(user.getLoginId());
		Dept dept = null;
		if (!userDepts.isEmpty()) {
			dept = userDepts.get(0);
		}
		if (null != dept) {
			userVo.setDept(dept.getName());
		} else {
			userVo.setDept("未知部门");
		}
		if (StringUtil.isEmpty(userVo.getDept()) || userVo.getDept().indexOf("特许厅") != -1) {
			throw new ActionException("特许厅人员无权登陆在线客服！");
		}
		userVo.setUsername(user.getUserName());
		if (null != userExt) {
			userVo.setIp(StringUtil.isNotEmpty(userExt.getIp()) ? userExt.getIp() : "暂无");
			userVo.setPhone(StringUtil.isNotEmpty(userExt.getMobile()) ? userExt.getMobile() : "暂无");
		}
		List<Role> roles = roleService.findRolesByUserId(user.getId());
		for (Role role : roles) {
			if (role.getId().equals("A2DF85A9626540E8B0B88228D4E24785")) {//座席 判断
				userVo.setJobCode(CONST.SEAT);
				break;
			} else if (role.getId().equals("C7DE711E032E48C4BAD65F9BC76A9665")) {//营业员 判断
				userVo.setJobCode(CONST.VISIT);
				break;
			}
		}
		if (StringUtil.isEmpty(userVo.getJobCode())) {
			throw new ActionException("未知员工信息！");
		}
		//获取用户所属聊天室
		List<GroupChat> groupChat = new ArrayList<GroupChat>();
		groupChat.addAll(groupChatService.getGroupChatsByUserid(user.getId()));
		userVo.setGroupChats(groupChat);
		TalkListener.USER_LIST.put(user.getId(), userVo);
		model.addAttribute("userjson", gson.toJson(userVo));
		model.addAttribute("userName", userVo.getUsername());
		initEnv(model);
		return "talk";
	}
	
	/**
	 * 附件上传
	 * @throws IOException 
	 *//*
	@RequestMapping(value = "/upload", method = {RequestMethod.POST} )
	@ResponseBody
	public String upload(ChatObject msg,HttpServletRequest request) {
		if (null == msg) {
			throw new ActionException("上传失败！");
		}
		if (StringUtil.isEmpty(msg.getToUser()) || StringUtil.isEmpty(msg.getFromUser())) {
			throw new ActionException("参数不能为空！");
		}
		UserVo fromUser = HallListener.findOnlineUserByUserId(msg.getFromUser());
		UserVo toUser = HallListener.findOnlineUserByUserId(msg.getToUser());
		if (null == fromUser || null == toUser) {
			throw new ActionException("无效的上传信息！");
		}
		//封装消息体
		msg.setFromUser(fromUser.getId());
		msg.setFromUserCode(fromUser.getLoginid());
		msg.setFromUserDept(fromUser.getDept());
		msg.setFromUserIp(fromUser.getIp());
		msg.setFromUserName(fromUser.getUsername());
		msg.setFromUserPhone(fromUser.getPhone());
		msg.setToUser(toUser.getId());
		msg.setToUserCode(toUser.getLoginid());
		msg.setToUserDept(toUser.getDept());
		msg.setToUserIp(toUser.getIp());
		msg.setToUserName(toUser.getUsername());
		msg.setToUserPhone(toUser.getPhone());
		try {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			List<MultipartFile> files = multiRequest.getMultiFileMap().get("file");
			//上传路径
			String savePath = SocketServer.getCharInfoOutPath();
			//文件名称
			String fileName = DateTimeUtil.dateToString(new Date(), "yyyyMMddHHmmssms");
			File file = null;
			HallListener hallListener = new HallListener();
			for (MultipartFile multipartFile : files) {
				//拼装文件名
				fileName = fileName+"+"+fromUser.getId()+"_TO_"+toUser.getId()+"+"+multipartFile.getOriginalFilename();
				//封装消息体
				msg.setFileName(multipartFile.getOriginalFilename());
				msg.setKey(SecurityUtil.encryptAES(fileName));
				msg.setFileSize(multipartFile.getSize());
				file = new File(savePath+fileName);
				//保存文件
				FileUtil.writeByteArrayToFile(file, multipartFile.getBytes());
				//上传后发送附件消息
				msg.setMessage("upLoadFile("+fileName+")");
				hallListener.upLoadSendMessage(request.getContextPath()+File.separator, msg);
			}
		} catch (Exception e) {
			throw new ActionException(e.getMessage());
		}
		return msg.getaHref();
	}*/
	
	/**
	 * 下载
	 */
	/*@RequestMapping(value = "/downl", method = {RequestMethod.POST,RequestMethod.GET} )
	public void downl(@RequestParam(value="key",required=false) String key,
			HttpServletRequest request, HttpServletResponse response){
		if (StringUtil.isEmpty(key)) {
			throw new ActionException("参数不能为空！");
		}
		BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
		try {
			key = SecurityUtil.decryptAES(key);
			//上传路径
			String savePath = SocketServer.getCharInfoOutPath();
			File file = new File(savePath+key);
			if (!file.isFile()) {
				throw new ActionException("文件不能存在！");
			}
			String[] keys = key.split("\\+");
			String fileName = keys[keys.length-1];
			response.setContentType("text/html;charset=UTF-8");
			request.setCharacterEncoding("UTF-8");
	        response.setHeader("Content-disposition", "attachment; filename="
	                + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
	        bis = new BufferedInputStream(new FileInputStream(file));
	        bos = new BufferedOutputStream(response.getOutputStream());
	        byte[] buff = new byte[2048];  
	        int bytesRead;
	        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
	            bos.write(buff, 0, bytesRead);
	        }
		} catch (Exception e) {
			throw new ActionException("下载失败！");
		} finally {
			try {
				if (null != bis) {
					bis.close();
				}
			} catch (Exception e2) {}
	        try {
	        	if (null != bos) {
	        		bos.close();
				}
			} catch (Exception e2) {}
		}
	}*/
}
